package com.azt.mq.service;

import com.azt.api.pojo.MailParam;
import com.azt.mq.listener.ConsumerSessionAwareMessageListener;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;

import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

@Component
public class MailService {
	
	
	
	private static final  Logger  log =LoggerFactory.getLogger(ConsumerSessionAwareMessageListener.class);
	
	
	@Autowired
	private JavaMailSender mailSender;// spring配置中定义
	
	
	@Autowired
	private SimpleMailMessage simpleMailMessage;// spring配置中定义
	
	
	@Autowired
	private ThreadPoolTaskExecutor threadPool;
	
	
	
	
	@Value("${sms.sign}")
	private String sign;
	/**
	 * 发送模板邮件
	 */
	public void mailSend(final MailParam mailParam) {
		threadPool.execute(new Runnable() {
			public void run() {
				try {
					
					MimeMessage mimeMessage = mailSender.createMimeMessage();
					MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage);
					if(StringUtils.isNotBlank(mailParam.getFrom())){
						String nick = javax.mail.internet.MimeUtility.encodeText(mailParam.getFrom()); 
						mimeMessageHelper.setFrom(new InternetAddress(nick + " <"+simpleMailMessage.getFrom()+">"));
					}else{
						mimeMessageHelper.setFrom(simpleMailMessage.getFrom());
					}
					
					String to = mailParam.getTo();
					if(StringUtils.isNotBlank(to)){
						String[] emails = to.split(",");
	//					mimeMessageHelper.setFrom(simpleMailMessage.getFrom());
						mimeMessageHelper.setTo(emails);
						mimeMessageHelper.setSubject(sign+" "+mailParam.getSubject());
						mimeMessageHelper.setText(mailParam.getContent(),true);
						mailSender.send(mimeMessage);
					}else{
						log.error("邮件目标不存在");
					}
				} catch (Exception e) {
					log.error("error", e);
					e.printStackTrace();
//					throw e;
				}
			}
		});
	}
}
